<template>
    <view ref="uv-back-top">
		<block v-if="(data_base || null) == null">
			<component-tj-skeletons ></component-tj-skeletons>
		</block> 
		<block v-else>
			<view v-if="(data_base || null) != null" :class="((data_base.is_show_mourning || 0) == 1 ? ' grayscale' : '') + (is_single_page == 1 ? ' single-page-top' : '')">
				<!-- #ifdef APP-PLUS -->
				<!-- 右侧icon -->
				<view v-if="is_agree_privacy && (plugins_fccprouniapp_data || null) != null && (plugins_fccprouniapp_data.base || null) != null && (plugins_fccprouniapp_data.base.is_app_home_share || null) != null && parseInt(plugins_fccprouniapp_data.base.is_app_home_share) === 1" class="top-share-right-icon">
					<uni-icons type="redo" size="20" color="#333" class="icon round cp" @tap="popup_share_event"></uni-icons>
				</view>
				<!-- #endif -->
				
				<!-- diy模式 -->
				<block v-if="data_mode == 3">
					<block v-if="data_list !== null">
						<componentDiy :propValue="data_list.config" :propDataId="data_list.id" :propKey="random_value" @onLocationBack="user_back_choice_location">
							<!-- 底部内容 -->
							<template slot="diy-bottom-content">
								<!-- 结尾 -->
								<component-bottom-line :propStatus="data_bottom_line_status"></component-bottom-line>
								<!-- 版权信息 -->
								<component-copyright></component-copyright>
							</template>
							<!-- 底部公共 -->
							<template slot="diy-bottom-common">
								<component-common ref="common" :propIsGrayscale="(data_base.is_show_mourning || 0) == 1"></component-common>
							</template>
						</componentDiy>
					</block>
					<block v-else>
						<component-no-data propStatus="0" propPage="home"></component-no-data>
					</block>
				</block>
				<block v-else>
					<!-- #ifdef MP-WEIXIN || MP-QQ || MP-KUAISHOU || H5 || APP-PLUS -->
					<!-- 小导航 -->
					<view class="top-nav-left-icon pf dis-none" :style="'top:' + top_nav_icon_top_value + 'px;'">
					    <uni-icons type="arrow-left" size="22" color="#333" class="icon round cp" @tap="top_nav_left_back_event"></uni-icons>
					</view>
					<!-- #endif -->
					
					<component-tj-header ref="tjheader" :propBaseData="data_base" propHeaderType="1" :propBannerList="slide_list" :propRightIcon="right_icon_list" @onLocationBack="user_back_choice_location" :propMofang="plugins_fccprouniapp_mofang" :propNavigation="category" :propSearchFixed="search_is_fixed" :propRandom="random_value" propFrom="classinfo" :diyTheme="diytheme" propUrl="/pages/fcc/classinfo/search/search"></component-tj-header>
					
					<view class="content padding-horizontal-main">
						<!-- 魔方-导航下方 - 插件 -->
						<block v-if="(plugins_fccprouniapp_mofang || null) != null">
							<component-mofang :propData="plugins_fccprouniapp_mofang" propLocation="15" propIsInContent="true"></component-mofang>
						</block>
						
						<!-- 商城公告 -->
						<view class="notice-content-box spacing-mb pr" v-if="load_status == 1 && data_base.classinfo_home_notice != ''">
							<uv-notice-bar :text="data_base.classinfo_home_notice"></uv-notice-bar>
						</view>
						
						<!-- 推荐文章 -->
						<view v-if="article_list.length > 0" class="article-list padding-main border-radius-main oh spacing-mb">
							<image :src="toutiao_img" mode="aspectFit" class="new-icon va-m fl cp"></image>
							<view class="right-content fr va-m">
								<swiper :vertical="true" :autoplay="true" :circular="true" display-multiple-items="1" interval="3000">
									<block v-for="(item, index) in article_list" :key="index">
										<swiper-item class="single-text">
											<text class="cr-base text-size-sm cp" :data-value="'/pages/fcc/classinfo/search/search?id='+item.gid" @tap="url_event">[{{item.goods_name}}]</text>
											<text class="cr-base text-size-sm margin-left-xs cp" :style="(item.title_color || null) != null ? 'color:'+item.title_color+' !important;' : ''" :data-value="item.url" @tap="url_event">{{item.title}}</text>
										</swiper-item>
									</block>
								</swiper>
							</view>
						</view>
						
						<!-- 魔方-分类信息推荐文章下方 - 插件 -->
						<block v-if="(plugins_fccprouniapp_mofang || null) != null">
							<component-mofang :propData="plugins_fccprouniapp_mofang" propLocation="16" propIsInContent="true"></component-mofang>
						</block>
					</view>
					
					<view class="big-shaixuan">
						<view class="big-shaixuan-box">
							<view class="big-shaixuan-tab-list">
								<view class="big-tab-item" :style="(bigactiveTab === 0) ? 'color:'+diytheme.main_color+';' : ''" @tap="setBigActiveTab(0)">
									<view class="t1">分类信息</view>
									<view class="xiahuaxian" :style="(bigactiveTab === 0) ? 'display:block;border-bottom:2px solid '+diytheme.main_color+';' : ''"></view>
								</view>
								<view class="big-tab-item" :style="(bigactiveTab === 1) ? 'color:'+diytheme.main_color+';' : ''" @tap="setBigActiveTab(1)">
									<view class="t1">本地商家</view>
									<view class="xiahuaxian" :style="(bigactiveTab === 1) ? 'display:block;border-bottom:2px solid '+diytheme.main_color+';' : ''"></view>
								</view>
							</view>
						</view>
					</view>
					<view v-if="bigactiveTab === 0">
						<view class="listings">
							<view class="listings-box">
								<scroll-view scroll-x class="tab-scroll" :scroll-x="true" :show-scrollbar="false">
									<view class="tab-list">
										<view v-for="(item, index) in index_data" :key="index" class="tab-item" :style="(activeTab === index) ? 
										'border-bottom:2px solid '+diytheme.main_color+';font-size:32rpx;font-weight:bold;line-height:55rpx;' : ''" @tap="setActiveTab(index)">{{ item.title }}</view>
									</view>
								</scroll-view>
							</view>
						</view>
						<view :class="'listing-content listing-content-'+data_base.index_list_style">
							<block v-for="(item, index) in index_data" :key="index">
								<view :style="(activeTab === index) ? 'display:block;' : 'display:none'">
									<component-tj-classinfo-list :diyTheme="diytheme" :propConfig="data_base" :propEmo="emoji_list" :propData="{...{data: item.data}, ...{random: random_value}}"></component-tj-classinfo-list>
								</view>
							</block>
						</view>
					</view>
					<view v-if="bigactiveTab === 1">
						<view v-if="shop_data.length > 0" :class="'listing-content listing-content-s'+data_base.index_list_style">
							<view v-for="(item2, index2) in shop_data" :key="item2.id">
							    <component-company-item :propConfig="data_base" :propData="item2"></component-company-item>
							</view>
						</view>
					</view>

					<!-- 结尾 -->
					<component-bottom-line :propStatus="data_bottom_line_status"></component-bottom-line>
					
					<!-- 版权信息 --> 
					<view v-if="load_status == 1">
						<component-copyright :propRandom="random_value"></component-copyright>
					</view>
					
					<!-- 在线客服 -->
					<component-online-service :propBacktottom="backbottom" :propIsNav="true" :propIsBar="true" :propIsGrayscale="(data_base.is_show_mourning || 0) == 1"></component-online-service>
					
					<!-- 快捷导航 -->
					<component-quick-nav :propBacktottom="backbottom" :diyTheme="diytheme" :propIsNav="true" :propIsBar="true" :propIsGrayscale="(data_base.is_show_mourning || 0) == 1"></component-quick-nav>
				</block>

				<!-- 分享弹窗 -->
				<component-share-popup :diyTheme="diytheme" ref="share"></component-share-popup>
				
				<!-- 公共 -->
				<component-common ref="common" :propIsGrayscale="(data_base.is_show_mourning || 0) == 1"></component-common>
			</view>
			<view v-else>
				<!-- 提示信息 -->
				<component-no-data :propStatus="data_list_loding_status" :propMsg="data_list_loding_msg"></component-no-data>
			</view>
			
			<!-- 发布、我的入口 -->
			<component-classinfo-footer :propBaseData="data_base"></component-classinfo-footer>
		</block>
    </view>
</template>
<script>
    const app = getApp();
	import componentQuickNav from "@/components/quick-nav/quick-nav";
    import componentNoData from '@/components/no-data/no-data';
    import componentBottomLine from '@/components/bottom-line/bottom-line';
	import componentClassinfoFooter from '../public/footer';
	import componentTjHeader from "../public/tj-header/tj-header";
	import componentTjSkeletons from '@/components/tj-skeletons/tj-skeletons';
	import componentDiy from '@/pages/diy/components/diy/diy';
	import componentMofang from "@/components/mofang/mofang";
	import componentSharePopup from "@/components/share-popup/share-popup";
	import componentTjClassinfoList from '@/components/tj-classinfo-list/tj-classinfo-list';
	import componentTitle from '@/components/title/title';
	import componentCopyright from "@/components/copyright/copyright";
	import componentCommon from '@/components/common/common';
	import {system_base_info, clear_user_cach} from "@/common/js/common/common";
	import componentCompanyItem from '../public/company-item';
	import componentOnlineService from "@/components/online-service/online-service";
	
	// 获取系统状态栏的高度
	var system_info = app.globalData.get_system_info() || {};
	var win_width = parseInt(system_info.windowWidth || system_info.screenWidth || 0);
	var bar_height = parseInt(system_info.statusBarHeight || 0);
	
	let menuButtonInfo = {};
	// 如果是小程序，获取右上角胶囊的尺寸信息，避免导航栏右侧内容与胶囊重叠(支付宝小程序非本API，尚未兼容)
	// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ || MP-ALIPAY
	menuButtonInfo = uni.getMenuButtonBoundingClientRect();
	// #endif
	
    export default {
        data() {
            return {
				plugins_fccprouniapp_data: null,
				diytheme: null,
				toutiao_img: app.globalData.get_static_url('classinfo', true)+'mini/toutiao.png',
				// 首页数据模式
				data_mode: 0,
				random_value: 0,
				load_status: 0,
				data_list: [],
				data_bottom_line_status: false,
				data_list_loding_status: 1,
				data_list_loding_msg: '',
				index_data: [],
				
				gid: 0,//类型ID 后期可以做切换，改变此参数，并进行请求
				info_list: [],
				data_total: 0,
				data_page_total: 0,
				data_page: 1,
				// 自定义分享信息
				share_info: {},
				common_app_is_header_nav_fixed: 0,
				common_app_is_enable_search: 0,
				user_temp:null,
				// 顶部+搜索样式配置
				top_content_search_bg_color: '',
				search_style: '',
				search_is_fixed: 0,
				is_fcc_tabber: false,
				scrollTop: 0,
				backbottom: 140,
				bottomsafetemp: 0,
				// 顶部导航信息
				// #ifdef MP || APP-PLUS
				top_nav_icon_top_value: bar_height + 8,
				// #endif
				// #ifdef H5
				top_nav_icon_top_value: 6,
				// #endif
                
				params: null,
                slide_list: [],
                data_base: null,
                category: [],
				article_list: [],
                classinfo_main_name:this.$t('fengcheche.classinfo.bigname'),
				message_total: 0,
				right_icon_list: [],
				plugins_fccprouniapp_mofang: null,

				// 是否单页预览
				is_single_page: app.globalData.is_current_single_page() || 0,
				static_url: app.globalData.get_static_url('home'),
				safeAreaInsets:app.globalData.get_system_info('safeAreaInsets'),
				is_agree_privacy: true,
				get_data_flag: false,
				
				activeTab: 0,
				// 用户位置信息
				user_location: {},
				emoji_list: [],
				
				bigactiveTab: 0,
				shop_data: [],
            };
        },

        components: {
            componentNoData,
            componentBottomLine,
			componentTjClassinfoList,
			componentClassinfoFooter,
			componentTjSkeletons,
			componentTjHeader,
			componentDiy,
			componentMofang,
			componentSharePopup,
			componentTitle,
			componentCopyright,
			componentQuickNav,
			componentCommon,
			componentCompanyItem,
			componentOnlineService
        },

        async onLoad(params) {
        	// 数据加载
        	this.init(); 
        },

        onShow() {
			app.globalData.page_event_onshow_handle();
			console.log('----->show 了');
			
			this.init_real();
			if(this.load_status == 0)
			{
				
			}
			
			// 用户位置初始化
			this.user_location_init();
        },

        // 下拉刷新
        onPullDownRefresh() {
            this.setData({
                data_page: 1
            });
			// 数据加载
			this.init_real();
        },
		// 页面滚动监听
		async onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// #ifdef APP-NVUE
			this.scrollTop = e.detail.scrollTop;
			// #endif
		    if(this.common_app_is_header_nav_fixed == 1 && this.common_app_is_enable_search == 1) {
		        var top = e.scrollTop > 35 ? 35 : e.scrollTop;
		        var num = top*7;
		        var base = 230;
		        // #ifdef MP-ALIPAY
		            base = 235
		        // #endif
		        // #ifdef H5 || MP-TOUTIAO || APP-PLUS
		            var len = (this.right_icon_list || []).length;
		            base = (len <= 0) ? 0 : 66*len;
		        // #endif
		        // 开启哀悼插件的时候不需要浮动导航并且搜索框也不需要缩短、开启站点灰度会导致浮动失效
		        if((this.data_base.is_show_mourning || 0) == 1) {
		            var top_val = 35;
		            var val = (num > base) ? base : num;
		            // #ifdef MP-TOUTIAO
		                top_val = 0;
		                val = base
		            // #endif
		            this.setData({
		                //search_style: 'width: calc(100% - '+val+'rpx);',
		                search_is_fixed: (top >= top_val) ? 1 : 0,
		            });
		        }
		    }
		},
        methods: {
			setActiveTab(tab) {
			    this.activeTab = tab;
			},
			setBigActiveTab(tab){
				this.bigactiveTab = tab;
			},
			// 开始
			init(is_mandatory = 0){
				system_base_info()
				.then(data=>{
					this.init_before(data)
					.then(()=>{
						this.init_real()
						.then(data=>{
							
							var title = data.base.seo_title || data.base.application_name;
							// 标题
							uni.setNavigationBarTitle({ title: title || this.classinfo_main_name});
							
							// 分享菜单处理
							app.globalData.page_share_handle();
							
							// #ifdef APP-PLUS
							if(this.is_agree_privacy){
								// 弹屏广告插件处理
								this.plugins_popupscreen_handle();
								
								// 公共onshow事件
								if(this.data_mode == 3) {
									if ((this.$refs.common || null) != null) {
										this.$refs.common.on_show();
									}
									
									// 设置顶部导航的默认颜色
									this.set_navigation_bar_color();
								}
							}
							// #endif
							// #ifndef APP-PLUS
							// 弹屏广告插件处理
							this.plugins_popupscreen_handle();
							
							// 公共onshow事件
							if(this.data_mode == 3) {
								if ((this.$refs.common || null) != null) {
									this.$refs.common.on_show();
								}
								
								// 设置顶部导航的默认颜色
								this.set_navigation_bar_color();
							}
							// #endif
						});
					});
				});
			},
			
			// 设置本页参数
			init_before(data){
				var self = this;
				return new Promise((resolve, reject) => {
					let open_search = app.globalData.get_config('config.common_app_is_enable_search');
					let is_agree_privacy = true;
					// #ifdef APP-PLUS
					if(!app.globalData.check_app_disagree_simple()){
						open_search = 0;//不同意协议强制不开启搜索
						is_agree_privacy = false;//未同意协议的标识
					}
					// #endif
					var is_fcc_tabber = ((data.base.is_close_foot_nav || null) != null && parseInt(data.base.is_close_foot_nav) == 1) ? false : true;
			
					var backbottom = 140;
			
					let bottomsafetemp = 0;
					if (this.safeAreaInsets && this.safeAreaInsets.hasOwnProperty('bottom'))
					{
						bottomsafetemp = parseInt(this.safeAreaInsets.bottom/2);
					}
			
					// 如果是DIY底部，且样式为0就是贴底显示而非悬浮底部的时候，微调数据
					if(!is_fcc_tabber)
					{
						let diy_app_tabber = app.globalData.get_config('app_tabber');
						if((diy_app_tabber || null) != null)
						{
							let diy_nav_type = diy_app_tabber.content.nav_type || 1;
							if(parseInt(diy_nav_type) == 0)
							{
								// #ifdef H5 || APP-PLUS
								bottomsafetemp += 10;
								// #endif
								// #ifdef MP
								// 小程序再微调10个数，分有无安全距离分别微调
								if(bottomsafetemp > 0)
								{
									bottomsafetemp += 23;
								}else{
									bottomsafetemp += 10;
								}
								// #endif
							}else{
								
							}
						}
					}
					
					self.setData({
						lang_info: data.system_lang_info,
						diytheme: data.diytheme,
						common_app_is_enable_search: open_search,
						common_app_is_header_nav_fixed: parseInt(app.globalData.get_config('config.common_app_is_header_nav_fixed')),
						user_temp: uni.getStorageSync(app.globalData.data.cache_user_info_key) || null,
						is_agree_privacy: is_agree_privacy,
						is_fcc_tabber: is_fcc_tabber,
						backbottom: backbottom,
						bottomsafetemp: bottomsafetemp,
					});
					resolve();
				});
			},
			
            // 得到分类的基础数据
            init_real(params = {}) {
				var self = this;
            	return new Promise((resolve, reject) => {
            		var old_load_status = this.load_status;
            		var upd_data = null;
            		// 还没有数据则读取缓
            		var cache_key = 'classinfo_home_data_key';
            		if(this.load_status == 0)
            		{
            		    // 本地缓存数据
            		    upd_data = uni.getStorageSync(cache_key) || null;
            		    if(upd_data != null) {
            		        // 先使用缓存数据展示
            		        this.setData(upd_data);
            		    }
            		}
            		// 已有本地缓存则直接取远程有效数据（默认首次取的是远程缓存数据）
            		params['is_cache'] = 0;
            		uni.request({
						url: app.globalData.get_request_url('index', 'index', 'classinfo'),
            			method: 'POST',
            			data: params,
            			dataType: 'json',
            			success: res => {
							console.log('index-index-data-');console.log(res.data);
            				// 设置首次加载状态
            				this.setData({
            					load_status: 1
            				});
            				if (res.data.code == 0) {
            					var data = res.data.data;
            					var data_list = data.data_list || null;
								var title = data.base.seo_title || data.base.application_name;
								var share_info = {
									title: title || this.classinfo_main_name,
									desc: data.base.seo_desc,
									path: '/pages/fcc/classinfo/index/index',
									img: (data.slide_list || null) != null && data.slide_list.length > 0 ? data.slide_list[0]['images_url'] : '',
								};
            					var udp = {
									random_value: Math.random(),
            						data_mode: data.data_mode || 0,
            						data_list: data_list,
            						data_base: data.base || null,
            						category: data.category || [],
									index_data: data.index_data || [],
            						slide_list: data.slide_list || [],
									article_list: data.article_list || [],
									plugins_fccprouniapp_mofang: data.mofang || null,
									share_info: share_info,
									message_total: parseInt(data.message_total || 0),
									right_icon_list: data.right_icon_list || [],
									emoji_list: data.emoji_list || [],
            					};
								if((data.shop_data || null) != null)
								{
									udp['shop_data'] = data.shop_data[0].data.data || [];
								}
								// 头条小图片
								var toutiao_pic = data.base.gonggao_images_url || '';
								var toutiao_img_temp = self.toutiao_img; 
								if(toutiao_pic != ''){
									toutiao_img_temp = toutiao_pic;
								}
								udp['toutiao_img'] = toutiao_img_temp;
								
            					this.setData(udp);
								
								// 基础信息存缓存
								uni.setStorageSync('classinfo_base_info_data_key', data.base);

            					// 存储缓存
            					uni.setStorageSync(cache_key, udp);

            					resolve(data); 
            				} else {
            					app.globalData.showToast(res.data.msg);
            					reject(res.data.msg);
            				}
            			},
            			fail: () => {
            				uni.stopPullDownRefresh();
            				this.setData({
            					load_status: 1
            				});
            				app.globalData.showToast(this.$t('common.internet_error_tips'));
            				reject('10004');
            			}
            		});
            	});
            },

			// 设置顶部导航的默认颜色
			set_navigation_bar_color() {
				if(this.data_mode == 3) {
					app.globalData.set_navigation_bar_color(parseInt(app.globalData.get_key_data(this.data_list, 'config.header.com_data.style.function_buttons_type', 0)) == 1);
				}
			},
			
			// 弹屏广告 - 后期使用分类的专用弹屏广告 - 来自于主题的设置
			plugins_popupscreen_handle() {

			},
			
			// 弹屏广告  关闭事件
			plugins_popupscreen_close_event(e) {
			    
			},
			
			// 选择用户地理位置回调
			user_back_choice_location(e) {
				// 设置数据
				this.setData({
				    user_location: e
				});
				console.log('回调了');
				// 重新刷新数据
				this.init();
			},
			
			user_location_init(){
				var self = this;
				var result = uni.getStorageSync(app.globalData.data.cache_userlocation_key) || null;
				if((result || null) == null)
				{
					//获取位置
					// #ifdef MP-WEIXIN
					wx.getFuzzyLocation({
						type: 'gcj02',
						success (res) {console.log(res);
							//const latitude = res.latitude
							//const longitude = res.longitude
							var res2 = {};
							res2['status'] = 1;
							res2['lat'] = res.latitude;
							res2['lng'] = res.longitude;
							
							// 根据位置获取城市ID，然后重载基础数据
							setTimeout(function () {
								self.getcityid(res2);
								//self.user_location_init_sec();
							}, 500);
						},
						fail(err){
							console.log(err);
						}
					});
					// #endif
					// #ifndef MP-WEIXIN
					this.user_location_init_sec();
					// #endif
				}else{
					this.user_location_init_sec();
				}
			},
			
			getcityid(e) {
				var that = this;
				// 根据经纬度请求到城市名字
				uni.request({
					url: app.globalData.get_request_url("getcityid", "index", "classinfo"),
					method: "POST",
					data: e,
					dataType: "json",
					success: res => {console.log(res);
						if(res.data.code == 0){
							// 定位成功，改写本地用户的temp_city
							uni.setStorageSync('user_city_info', res.data.data);
							
							var res2 = e;
							res2['name'] = res.data.data.city_name;
							res2['address'] = res.data.data.city_name;
							res2['status'] = 1;
							uni.setStorageSync(app.globalData.data.cache_userlocation_key, res2);
							setTimeout(function () {
								that.user_location_init_sec();
							}, 500);
							/*that.setData({
								city_id: res.data.data.city_id,
								city_name: res.data.data.city_name,
							});*/
						}
					},
					fail: () => {
						app.showToast("请求城市名字出错");
					}
				});
			},
			
			// 地址信息初始化
			user_location_init_sec() {
			    var res = app.globalData.choice_user_location_init();console.log(res);
			    this.setData({
			        user_location: res
			    });
				if ((this.$refs.tjheader || null) != null) {
					this.$refs.tjheader.init();
				}
				this.init();
			},
			
			// 分享开启弹层
			popup_share_event(e) {
				if ((this.$refs.share || null) != null) {
					this.$refs.share.init({
						status: true,
						share_info: app.globalData.share_content_handle({})
					});
				}
			},
			
			// 返回事件
			top_nav_left_back_event(e) {
			    app.globalData.page_back_prev_event();
			},

            // url事件
            url_event(e) {
                app.globalData.url_event(e);
            },
        },
    };
</script>
<style>
    @import './index.css';
</style>
